package com.yao.fin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yao.common.bean.PageQueryBean;
import com.yao.common.enums.business.fin.CourseBase;
import com.yao.common.enums.business.fin.LabelEnum;
import com.yao.common.helper.ValidateHelper;
import com.yao.common.resp.ApiResponse;
import com.yao.fin.entity.dto.FinancialTemplateDto;
import com.yao.fin.service.FinancialTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 财务模版表 Controller
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-04-09
 */
@Api(tags = "会学管理")
@RestController
@RequestMapping(value = "/financialTemplate")
@Slf4j
public class FinancialTemplateController {

    @Autowired
    private FinancialTemplateService financialTemplateService;

    @ApiOperation(value = "新增会学", notes = "新增会学")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ApiResponse<Object> add(@RequestBody FinancialTemplateDto model) {
        model.setQuestion(this.parseStr(model.getQuestion()));
        financialTemplateService.save(model);
        return ApiResponse.success();
    }

    @ApiOperation(value = "修改会学", notes = "修改会学")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ApiResponse<Object> update(@RequestBody FinancialTemplateDto model) {

        model.setQuestion(this.parseStr(model.getQuestion()));

        financialTemplateService.updateById(model);
        return ApiResponse.success();
    }

    @ApiOperation(value = "删除会学", notes = "逻辑删除会学")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public ApiResponse<Object> deleteById(@PathVariable("id") Integer id) {

        ValidateHelper.validateId(id);

        financialTemplateService.removeById(id);

        return ApiResponse.success();
    }

    @ApiOperation(value = "获取详情", notes = "获取详情")
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public ApiResponse<FinancialTemplateDto> detail(@PathVariable("id") Integer id) {

        return ApiResponse.success(financialTemplateService.getById(id));
    }

    @ApiOperation(value = "会学列表(分页)", notes = "会学列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ApiResponse<IPage<FinancialTemplateDto>> list(@RequestBody PageQueryBean<FinancialTemplateDto> queryBean) {


        return ApiResponse.success(financialTemplateService.page(new Page<>(queryBean.getCurrent(), queryBean.getSize()), queryBean.getData()));
    }

    @ApiOperation(value = "科目查询", notes = "科目查询")
    @GetMapping("/listCourse/{label}")
    public ApiResponse<List<Map<String, String>>> listCourse(@PathVariable("label") LabelEnum label) {


        List<Map<String, String>> list = CollUtil.newArrayList();

        if (label == LabelEnum.ZJ) {
            CourseBase.ZJEnum.getEnums().forEach((k, v) -> {
                HashMap<String, String> map = CollUtil.newHashMap();

                map.put("id", k.toString());
                map.put("name", v);
                list.add(map);
            });
        }else if(label == LabelEnum.CPA){
            CourseBase.CPAEnum.getEnums().forEach((k, v) -> {
                HashMap<String, String> map = CollUtil.newHashMap();

                map.put("id", k.toString());
                map.put("name", v);
                list.add(map);
            });
        }

        return ApiResponse.success(list);
    }

    @ApiOperation(value = "导出", notes = "导出")
    @PostMapping("/export")
    public ApiResponse<Object> export(@RequestBody FinancialTemplateDto qo, HttpServletResponse response) throws IOException {
        Console.log(" 导出 文本 条件：{}", qo);

        ValidateHelper.validateNull(qo, new String[]{"label"});

        return ApiResponse.success(financialTemplateService.export(qo, response));
    }

    @ApiOperation(value = "文件下载", notes = "文件下载")
    @GetMapping("/download")
    public String download(@RequestParam("label") Integer label, @RequestParam("dateType") Integer dateType, HttpServletResponse response) throws IOException {

        FinancialTemplateDto qo = new FinancialTemplateDto();
        qo.setLabel(LabelEnum.getEnumByCode(label));
        qo.setDateType(dateType);

        return financialTemplateService.export(qo, response);
    }

    @ApiOperation(value = "上传", notes = "上传")
    @PostMapping("/upload")
    public ApiResponse<FinancialTemplateDto> upload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {

        FinancialTemplateDto upload = financialTemplateService.upload(file);

        return ApiResponse.success(upload);
    }


    private String parseStr(String msg){

        StringBuilder builder =  StrUtil.builder(StrUtil.replaceChars(msg, "/\n/g", ""));
        List<Integer> list = CollUtil.newArrayList();

        int fIdx = this.indexOf(builder, 'F');
        int eIdx = this.indexOf(builder, 'E');
        int dIdx = this.indexOf(builder, 'D');
        int cIdx = this.indexOf(builder, 'C');
        int bIdx = this.indexOf(builder, 'B');
        int aIdx = this.indexOf(builder, 'A');

        if(fIdx != -1){
            list.add(fIdx);
        }
        if(eIdx != -1){
            list.add(eIdx);
        }
        if(dIdx != -1){
            list.add(dIdx);
        }
        if(cIdx != -1){
            list.add(cIdx);
        }
        if(bIdx != -1){
            list.add(bIdx);
        }
        if(aIdx != -1){
            list.add(aIdx);
        }
        list.stream().forEach(e -> builder.insert(e, "\n"));

        return builder.toString();
    }

    private int indexOf(StringBuilder str, char c){
        int index = -1;
        int idx = StrUtil.indexOf(str, c);
        String sub = StrUtil.sub(str, idx+1, idx+2);
        // 答案列表必须是带有.或者、的。 比如A. B、 否则无法进行换行
        boolean flag = idx != -1 && (sub.equals(StrUtil.DOT) || sub.equals("、"));
        if(flag){
            index = idx;
        }

        return index;
    }


}